import { post, get } from '@/api/ajax'
import API from '@/api/apis'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { encryption } from '../../utils/rsa'
import WLog from '../../utils/YBLog/index'


const admin = {
  state: {
    /**
     * token
     */
    token: getToken(),
    /**
     * 用户名
     */
    name: '',
    /**
     * 头像
     */
    icon: ''
  },

  mutations: {
    /**
     * 设置token
     */
    SET_TOKEN: (state, token) => {
      state.token = token
      if (token) {
        setToken(token)
      } else {
        removeToken()
      }
    },
    /**
     * 设置用户数据
     */
    SET_USER_INFO: (state, userInfo) => {
      state.name = userInfo.user
      state.icon = userInfo.icon
      WLog.userName = userInfo.user
    }
  },

  actions: {
    /**
     * 登录
     * @param commit
     * @param userInfo
     * @returns {Promise<any>}
     * @constructor
     */
    LOGIN ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        post(API.auth.login, {
          user: userInfo.user,
          pass: encryption(userInfo.pass)
        }).then(data => {
          // const md5Pass = md5
          commit('SET_TOKEN', data.token)
          commit('SET_USER_INFO', data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
     * 获取用户信息
     * @param commit
     * @returns {Promise<any>}
     * @constructor
     */
    GET_USER_INFO ({ commit }) {
      return new Promise((resolve, reject) => {
        get(API.auth.getUserInfo).then(data => {
          commit('SET_USER_INFO', data)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
     * 修改用户数据
     * @param _
     * @param userInfo
     * @returns {Promise<any>}
     * @constructor
     */
    MODIFY_USER_DATA (_, userInfo) {
      return new Promise((resolve, reject) => {
        post(API.auth.modify, {
          icon: userInfo.icon,
          pass: userInfo.pass,
          user: userInfo.name
        }).then((data) => {
          resolve(data)
        }).catch((err) => {
          reject(err)
        })
      })
    },
    /**
     * 登出
     * @param commit
     * @returns {Promise<any>}
     * @constructor
     */
    LOG_OUT ({ commit }) {
      return new Promise((resolve, reject) => {
        get(API.auth.logOut).then(() => {
          commit('SET_TOKEN', null)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
     * 前端 登出
     * @param commit
     * @constructor
     */
    FED_LOG_OUT ({ commit }) {
      commit('SET_TOKEN', null)
    }
  }
}

export default admin
